import React from "react";
import querystring from "querystring";
import {inject, observer} from "mobx-react";
import FormView from './FormView';
import {WeaLocaleProvider} from 'ecCom';
import ThemeContext from "../theme";

const getLocaleLabel = WeaLocaleProvider.getLocaleLabel.bind(this, 'edc');
const { Provider } = ThemeContext;

@inject('edcFormViewStore')
@observer
export default class FormViewPage extends React.Component {
  constructor(props) {
    super();

    const key = this.getParamKey() || this.getKey(location.pathname) || this.getKey(location.hash);

    this.store = props.edcFormViewStore;

    this.store.init(key);

    this.initOauthKey();
  }

  componentWillMount(){
    getLocaleLabel();
  }

  initOauthKey() {
      const search = location.search.replace('?', '');
      let { code } = querystring.parse(search);
      code && this.store.initOauthKey(code);
  }

  getParamKey() {
    const search = location.search.replace('?', '');
    let { _key } = querystring.parse(search);

    return _key;
  }

  getKey(str) {
    const matches = str.match(/\/edc\/formview\/\w+/g);

    if (!matches) return;

    const key = matches[0].match(/\/[^\/]*?$/);

    return key && key[0].replace(/^\//, '');
  }

  render() {
    const {theme} = this.store;
    return (
      <Provider value={theme}>
        <FormView store={this.store} />
      </Provider>
    );
  }
}